﻿using DadayunApi.Model;
using DadayunSync.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DadayunSync
{
    public partial class ApiTester : Form
    {
        DadayunApi.Api api = null;
        AppAuthBase appAuth = null;
        string baseUri = "https://api.dadayun.cn";
        public ApiTester()
        {
            InitializeComponent();
        }

        private void TestApi_Load(object sender, EventArgs e)
        {
            appAuth = new AppAuthBase
            {
                AppKey = "c514ea09ccdd4435a636443c0331d438",
                AppSecret = "c7ea1d12c4dd456f9019c47ed638b4b3",
                Username = "admin",
                Password = "kbT8046",
                TenantName="kenbotong",
                PublicKey= "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuFXMJ+EEgSGCXSy5ORYAUX1yn3tCGC6xCvJACcyK9cwqc5Wglp2cAY7dqrXUH8AJD+kwSTFMxPWeusl6i8JuJB0bktSmgqBhhq979DbSotZqOWAjRUNzGeph/fTXUDIzZ8AvNZOCUcHbIZP//60QWCc7fsEDPRBgStpIgXA03KL63AWyMbU92sXe/rLN1nxAkgzRLOcL87NdQTNBpHYRIoIp1OP7chXzLOq+J4ZfNHhR7bLujIg8M0C42ZIjl52YV7m4D69ZzChDW+1/zWXHl35I8kOjvH+1rjlkaq1kKO5vJ4ROeHAhSJOjQ4Jjz5zfXKGiXg9F6yp7zpfvUzpuDQIDAQAB"
            };
            api = new DadayunApi.Api(appAuth, baseUri);

            txtToken.Text = api.Token;
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            var obj = api.GetFormTemplateList();
            dgvData.DataSource = obj;
            #region GetMenuItems
            //var list = api.GetMenuItems(null, false, true);
            //dgvData.DataSource = null;
            //dgvData.DataSource = list; 
            #endregion
        }
        private void DisplayDictionary(DataGridView view,Dictionary<string,string> keyValues)
        {
            view.Columns.Clear();
            view.Columns.Add("colKey", "Key");
            view.Columns.Add("colValue", "Value");
            foreach (var k in keyValues.Keys)
            {
                view.Rows.Add(k, keyValues[k]);
            }
        }

        #region 调试器
        private void btnQuery_Click(object sender, EventArgs e)
        {
            if (cbMethod.Text.ToLower() == "get")
            {
                lbStatus.Text = api.HttpGet(txtFullUri.Text, out string json).ToString();
                txtResult.Text = json;
            }
            else if (cbMethod.Text.ToLower() == "post")
            {
                Dictionary<string, string> keyValues = new Dictionary<string, string>();
                foreach (DataGridViewRow r in dgvParams.Rows)
                {
                    if (r.Cells["colKey"].Value != null && r.Cells["colValue"].Value != null)
                        keyValues.Add(r.Cells["colKey"].Value.ToString(), r.Cells["colValue"].Value.ToString());
                }
                var content = new FormUrlEncodedContent(keyValues);
                lbStatus.Text = api.HttpPost(txtUri.Text, content, out string json).ToString();
                txtResult.Text = json;
            }
            else if (cbMethod.Text.ToLower() == "put")
            {
                Dictionary<string, string> keyValues = new Dictionary<string, string>();
                foreach (DataGridViewRow r in dgvParams.Rows)
                {
                    if (r.Cells["colKey"].Value != null && r.Cells["colValue"].Value != null)
                        keyValues.Add(r.Cells["colKey"].Value.ToString(), r.Cells["colValue"].Value.ToString());
                }
                var content = new FormUrlEncodedContent(keyValues);
                lbStatus.Text = api.HttpPut(txtUri.Text, content, out string json).ToString();
                txtResult.Text = json;
            }
        }

        private void dgvParams_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            txtFullUri.Text = BuildFullUri();
        }
        private string BuildFullUri()
        {
            string furi = "";
            switch (cbMethod.Text.ToLower())
            {
                case "get":
                    string cond = "?";
                    foreach (DataGridViewRow r in dgvParams.Rows)
                    {
                        if (r.Cells["colKey"].Value != null && r.Cells["colValue"].Value != null)
                            cond += r.Cells["colKey"].Value + "=" + r.Cells["colValue"].Value + "&";
                    }
                    furi = txtUri.Text + cond.Substring(0, cond.Length - 1);
                    break;
                default:
                    break;
            }
            return furi;
        }
        private void txtUri_Validated(object sender, EventArgs e)
        {
            txtFullUri.Text = BuildFullUri();
        }

        private void stGetProductProperties_Click(object sender, EventArgs e)
        {
            var obj = api.GetProductPropertySets();
            var obj1 = api.GetProductProperties(txtFormTplName.Text, obj[0].ProductNumberFieldId, obj[0].ProductFormId);
            txtEcho.Text = JsonConvert.SerializeObject(obj1);
            DisplayDictionary(dgvData, obj1);
        } 
        #endregion

        #region 表单功能
        private void stGetFormTplInfo_Click_1(object sender, EventArgs e)
        {
            var obj = api.GetFormTemplateList();
            dgvData.DataSource = null;
            dgvData.DataSource = obj;
        }

        private void stGetFormTpl_Click(object sender, EventArgs e)
        {
            FormTlpInfo obj = api.GetFormTemplate(txtFormTplName.Text);
            if(obj!=null)
            txtEcho.Text = api.ResponseJson;
        }

        private void stGetFormTplPermision_Click(object sender, EventArgs e)
        {
            var obj = api.GetFormTplPermission(txtFormTplName.Text, false);
            txtEcho.Text = api.FullUri + "\r\n";
            txtEcho.Text += JsonConvert.SerializeObject(obj);
        }

        

        private void stGetFormInstanceList_Click(object sender, EventArgs e)
        {
            var obj = api.GetFormList(txtFormTplName.Text, out int totalCount, 0, 20, null);
            txtEcho.Text = api.FullUri + "\r\n";
            dgvData.DataSource = null;
            dgvData.DataSource = obj;
        }

        private void stGetFormInstance_Click(object sender, EventArgs e)
        {
            var list = api.GetFormList(txtFormTplName.Text, out int totalCount, 0, 20);

            if (list.Count > 0)
            {
                var obj = api.GetFormInstance(txtFormTplName.Text, list[0].Id, EKeyOptions.Caption);
                txtEcho.Text = api.FullUri + "\r\n";
                txtEcho.Text += obj;

            }
        }

        private void stCreateFormInstance_Click(object sender, EventArgs e)
        {
            var obj = api.CreateFormInstance(txtFormTplName.Text, txtPostData.Text,out string instanceId, true, EAutoFillMode.ForceAll, EKeyOptions.Entity);
            txtEcho.Text = obj.ToString() + "\r\n";
            txtEcho.Text = api.ResponseJson;
        }

        private void stEditFormInstance_Click(object sender, EventArgs e)
        {
            var obj = api.EditFormInstance(txtFormTplName.Text, txtInstanceId.Text, txtPostData.Text, true, EAutoFillMode.ForceAll, EKeyOptions.Entity);
            txtEcho.Text = obj.ToString() + "\r\n";
            txtEcho.Text = api.ResponseJson;

        }

        private void stDeleteFormInstance_Click(object sender, EventArgs e)
        {
            var ans = api.DeleteFormInstance(txtFormTplName.Text, txtInstanceId.Text);
            txtEcho.Text = ans.ToString();
        } 
        #endregion
        #region Report API

        private void stGetReportTplList_Click(object sender, EventArgs e)
        {
            var obj = api.GetReportTemplateInfoes(0, 20, "Name");
            txtEcho.Text = api.FullUri + "\r\n";
            dgvData.DataSource = null;
            dgvData.DataSource = obj;
        }
        private void 获取报表模板ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var obj = api.GetReportTemplateDetails(txtFormTplName.Text);
            txtEcho.Text = JsonConvert.SerializeObject(obj);
        }
        private void 查询报表数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string json = api.GetReportInJson("产品库存报表", out int count, EKeyOptions.FieldName);

            //返回报表数据的json格式
            var ans = api.GetReportInJson(txtFormTplName.Text, out int totalCount, EKeyOptions.FieldName);
            txtEcho.Text = ans; //回显
            //实例化, 注意实体对应的字段(F2==报销部门等) ,应该在类中做定义
            BaoxiaoReport report = JsonConvert.DeserializeObject<BaoxiaoReport>(ans);
            dgvData.DataSource = null;
            dgvData.DataSource = report.Results;
        }

        #endregion
        #region 杂项
        private void getTokenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var token = api.GetToken();
            txtEcho.Text = JsonConvert.SerializeObject(token);
            api.SetToken(token);
        }

        private void 获取服务器时间ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtEcho.Text = api.GetServerTime().ToString();
        }



        private void 检查账号是否存在ToolStripMenuItem_Click(object sender, EventArgs e)
        {//不可用
            var ans = api.IsAcountExist("kenbotong", "ccjungle");
            string msg = "HttpStatus: " + api.HttpStatus;
            msg += "\r\nExist: " + ans;
            msg += "\r\nResponse Json: " + api.ResponseJson;
            txtEcho.Text = msg;
        }

        private void 获取角色下用户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var roles = api.GetRoleInfo();//获取所有角色

            var ans = api.GetUsersOfRole(roles[11].Id);
            string msg = "HttpStatus: " + api.HttpStatus;
            msg += "\r\nExist: " + ans;
            msg += "\r\nResponse Json: " + api.ResponseJson;
            txtEcho.Text = msg;
            dgvData.DataSource = null;
            dgvData.DataSource = ans;
        }

        private void stGetRols_Click(object sender, EventArgs e)
        {
            var ans = api.GetRoleInfo();//获取所有角色
            dgvData.DataSource = null;
            dgvData.DataSource = ans;
            var ans1 = api.GetRoleInfo(ans[0].Id);//获取指定ID的角色信息
            txtEcho.Text = JsonConvert.SerializeObject(ans1);
        }

        private void 获取当前登陆用户信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Login_Info ans = api.GetLoginInfo();
            txtEcho.Text = "UserInfo to Json:\r\n" + api.ResponseJson;
        }

        private void 获取角色的岗位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var roles = api.GetRoleInfo();//获取所有角色

            var ans = api.GetPositionsOfRole(roles[11].Id);
            string msg = "HttpStatus: " + api.HttpStatus;
            msg += "\r\nExist: " + ans;
            msg += "\r\nResponse Json: " + api.ResponseJson;
            txtEcho.Text = msg;
            dgvData.DataSource = null;
            dgvData.DataSource = ans;
        } 
        #endregion

        private void 获取用户tokenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ans= api.GetUserToken("7abc46e4-8f1e-4920-bfb1-2ba3b4970ec4","");
            string msg = "URL: " + api.FullUri;
            msg += "HttpStatus: " + api.HttpStatus;
            msg += "\r\nExist: " + ans;
            msg += "\r\nResponse Json: " + api.ResponseJson;
            txtEcho.Text = msg;
        }

        private void 根据产品属性获取产品编码ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 获取字典数据源ToolStripMenuItem_Click(object sender, EventArgs e)
        {
           var list= api.GetDictionaryItems("所属区域");
            dgvData.DataSource = null;
            dgvData.DataSource = list;
        }

        private void 获取区域ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var list = api.GetAreas("A0860000");
            dgvData.DataSource = null;
            dgvData.DataSource = list;
        }

        private void 获取菜单列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var list = api.GetMenuItems();
            dgvData.DataSource = null;
            dgvData.DataSource = list;
        }
    }
}
